package com.qq.Servlet.Book;


import com.qq.model.Book;
import com.qq.util.DBUtil;

import javax.print.DocFlavor;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
//center过滤器的注解
@WebServlet("/center/book/edit")
public class BookUpdateServlet extends HttpServlet {

    //显示某书的表单
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获得id
                        int id= Integer.parseInt(req.getParameter("id"));
      //查出这本书，填入到表单
        Connection con = DBUtil.getConnection();
        try{
            //问号代表给出的id
            PreparedStatement ps = con.prepareStatement("select *from book where id=?");
            ps.setInt(1,id);
            //ResultSet记录集，将数据存到里面去
            ResultSet rs = ps.executeQuery();
            if (rs.next()){
                //通过id进行查询获取下面的数据，这里是假设一定有书的
                //我们要使用就要将我们的数据给变量名
               int id1 = rs.getInt("id");
                String name = rs.getString("name");
                String author = rs.getString("author");
                double price = rs.getDouble("price");
                //这里是new一个Book对象
                Book book =new Book(id,name,author,price);
                //setAttribute在一个请求域里加一个请求参数
                //这里是将数据填写到修改的页面，因为el表达式可以直接用"book"双引号里的
               req.setAttribute("book",book);
            }
            //这里是判断没书的时候进行判断
//            else {
//
//            }
        }catch (SQLException e){
            e.printStackTrace();
        }
      req.getRequestDispatcher("/WEB-INF/jsp/book/update.jsp").forward(req,resp);

    }
//进行数据修改
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("utf-8");
        //将新数据进行提交
        String id  = req.getParameter("id");
        String name = req.getParameter("name");
        String author = req.getParameter("author");
        String price = req.getParameter("price");
        Connection con = DBUtil.getConnection();
        try{
            PreparedStatement ps = con.prepareStatement("update book set name =?,author = ?,price=? where  id=?");
            ps.setString(1,name);
            ps.setString(2,author);
            ps.setString(3,price);
            ps.setString(4,id);
            //数字num代表修改了多少行数据
           int num = ps.executeUpdate();
            System.out.println("===>"+num);
          resp.sendRedirect("index01");
        }catch (SQLException e){
            e.printStackTrace();
        }

    }
}
